package cn.bugstack.xfg.dev.tech.domain.controller;

import cn.bugstack.xfg.dev.tech.domain.order.model.aggregate.OrderAggregate;
import cn.bugstack.xfg.dev.tech.domain.order.model.entity.OrderEntity;
import cn.bugstack.xfg.dev.tech.domain.order.model.entity.SKUEntity;
import cn.bugstack.xfg.dev.tech.domain.order.model.entity.UserEntity;
import cn.bugstack.xfg.dev.tech.domain.order.model.valobj.DeviceVO;
import cn.bugstack.xfg.dev.tech.domain.order.service.IOrderService;
import cn.bugstack.xfg.dev.tech.infrastructure.redis.IRedisService;
import cn.hutool.core.lang.UUID;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author 公众号: SimpleMemory
 * @version 1.0.0
 * @ClassName OrderController.java
 * @Description TODO
 * @createTime 2023年09月12日 11:11:00
 */
@RestController
@RequestMapping
@Slf4j
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    IRedisService iRedisService;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    private final AtomicLong totalExecutionTime = new AtomicLong(); // 记录总耗时

    /**
     * 创建订单
     *
     * @return
     */
    @GetMapping
    @SneakyThrows
    public String test() {
        String sku = RandomStringUtils.randomNumeric(9);
        int count = 3;

        //
        log.error("key = {},value = {}", sku, count);
        orderService.initSkuCount(sku, count);

        for (int i = 0; i < count; i++) {
            String uuid = UUID.fastUUID().toString();
            threadPoolExecutor.execute(() -> {
                UserEntity userEntity = UserEntity.builder()
                        .userId(uuid)
                        .userName("小小开发者".concat(RandomStringUtils.randomNumeric(3)))
                        .userMobile("+86 13521408***")
                        .build();

                SKUEntity skuEntity = SKUEntity.builder()
                        .sku(sku)
                        .skuName("《手写MyBatis：渐进式源码实践》")
                        .quantity(1)
                        .unitPrice(BigDecimal.valueOf(128))
                        .discountAmount(BigDecimal.valueOf(50))
                        .tax(BigDecimal.ZERO)
                        .totalAmount(BigDecimal.valueOf(78))
                        .build();

                DeviceVO deviceVO = DeviceVO.builder()
                        .ipv4("127.0.0.1")
                        .ipv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334".getBytes())
                        .machine("IPhone 14 Pro")
                        .location("shanghai")
                        .build();

                long threadBeginTime = System.currentTimeMillis(); // 记录线程开始时间

                // 耗时:4毫秒
//                 String orderId = orderService.createOrder(new OrderAggregate(userEntity, skuEntity, deviceVO));
                // 耗时:106毫秒
//                String orderId1 = orderService.createOrderByLock(new OrderAggregate(userEntity, skuEntity, deviceVO));
                // 耗时:4毫秒
                String orderId2 = orderService.createOrderByNoLock(new OrderAggregate(userEntity, skuEntity, deviceVO));
                long took = System.currentTimeMillis() - threadBeginTime;
                totalExecutionTime.addAndGet(took); // 累加线程耗时
                log.info("写入完成 {} 耗时 {} (ms)", orderId2, took / 1000);
            });
        }

        new Thread(() -> {
            while (true) {
                if (threadPoolExecutor.getActiveCount() == 0) {
                    log.info("执行完毕，总耗时：{} (ms)", (totalExecutionTime.get() / 1000));
//                    log.info("执行完毕，总耗时:{}", "\r\033[31m" + (totalExecutionTime.get() / 1000) + "\033[0m");
                    break;
                }
            }
        }).start();

        // 等待
//		new CountDownLatch(1).await();

        return "success";

    }

    /**
     * 数据分页查询
     *
     * @param pageNo
     * @param pageSize
     */
    @GetMapping("/list/{pageNo}/{pageSize}")
    public List<OrderEntity> list(@PathVariable("pageNo") int pageNo, @PathVariable("pageSize") int pageSize) {
        orderService.initSkuCount("xxxxxxx", 23);

        long decrCount = iRedisService.decr("xxxxxxx");

        return orderService.list(pageNo, pageSize);
    }
}
